{include 'header.tpl'}
<div class="contant">
    <div class="header" style="height: 70px;">
        <div class="header_s">
            <span class="form_back"><a target="_blank" href="javascript:history.go(-1);"><i class="iconfont fan">&#xe679;</i></a></span>
            <div class="search" style="margin-top: 0;">
                <div class="region">长沙市<i></i></div>
                <div class="sr_region"><input type="search" id="search" placeholder="请输入您的收货地址" class=""></div>
            </div>
            <button class="sear_btn">搜索</button>
        </div>
    </div>

    <form name="myForm">
        <input id="string_x" type="hidden" name="myHidden" value="{$string_x}"/>
        <input id="string_y" type="hidden" name="province" value="{$string_y}"/>
    </form>

    <div id="allmap" style="width: 100%;height: 300px;"></div>

    <div class="loc">
        <div class="loc_tlt">附近地址</div>
        <div class="loc_list">
            <ul id="wordMap"></ul>
        </div>
    </div>
</div>
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script type="application/javascript" src='http://api.map.baidu.com/api?v=2.0&ak=pRtqXqnajTytAzWDL3HOnPRK'></script>
<script>
    var refer= '{$smarty.get.refer}';
</script>
{literal}
    <script>
        //delCookie('_base');
        //获取当前位置
        function getQueryString(queryname) {
            var qKeys = { };
            var re = /[?&]([^=]+)(?:=([^&]*))?/g;
            var matchInfo;
            while (matchInfo = re.exec(location.search)) {
                qKeys[matchInfo[1]] = matchInfo[2];
            }
            return typeof (qKeys[queryname]) == 'undefined' ? '0' : qKeys[queryname];
        }
        var id=getQueryString('id');
        var contact=getQueryString('contact');
        var phone=getQueryString('phone');
        var sex=getQueryString('sex');
        var housemember=getQueryString('housemember');
        var county=getQueryString('county');
        var string_x=$('#string_x').val();
        var string_y=$('#string_y').val();
        //        alert(string_x);
        //        alert(string_y);

        wx.config({
            debug: false,
            appId: '{$data.appid}',
            timestamp: '{$data.timestamp}',
            nonceStr: '{$data.nonceStr}',
            signature: '{$data.signature}',
            jsApiList: ["getLocation"],
        });

        /*wx.ready(function () {
            wx.getLocation({
                type: "wgs84",
                success: function (wx_res) {
                    if (wx_res.errMsg == "getLocation:ok") {
                        // 通过百度api转换当前经纬度坐标
                        $.ajax({
                            url: "http://api.map.baidu.com/geocoder/v2/?",
                            type: "get",
                            data: {
                                coordtype: 'wgs84ll',
                                location: wx_res.latitude + "," + wx_res.longitude,
                                ak: 'pRtqXqnajTytAzWDL3HOnPRK',
                                //callback: 'renderReverse',
                                output: 'json',
                                pois: 1
                            },
                            async: false,
                            dataType: "jsonp",
                            success: function (geo_res) {
                                var option = {};
                                if (geo_res.status != 0) {
                                    //alert('转换失败!');
                                    return;
                                }*/
                                var map = new BMap.Map("allmap");
                                var lng = '';
                                var lat = '';
                                /*var lng = geo_res.result.location.lng || '';
                                var lat = geo_res.result.location.lat || '';*/


                                map.centerAndZoom(new BMap.Point(lng,lat),16);
                                map.enableScrollWheelZoom(true);

                                var geolocation = new BMap.Geolocation();
                                geolocation.getCurrentPosition(function(r){

                                    if(this.getStatus() == BMAP_STATUS_SUCCESS){
                                        var mk = new BMap.Marker(r.point);
                                        map.addOverlay(mk);
                                        map.panTo(r.point);
                                        string_x = r.point.lng;
                                        string_y = r.point.lat;
                                        getPois(r.point.lng,r.point.lat);
                                    }
                                    else {
                                        $.alert('failed'+this.getStatus());
                                    }
                                },{enableHighAccuracy: true});

                                //红点定位 获取经纬度
                                map.addEventListener("click",function(e){
                                    getPois(e.point.lng ,e.point.lat);
                                    map.clearOverlays();
                                    var new_point = new BMap.Point(e.point.lng,e.point.lat);
                                    var marker = new BMap.Marker(new_point);
                                    map.addOverlay(marker);
                                    map.panTo(new_point);

                                    var geolocation = new BMap.Geolocation();
                                    geolocation.getCurrentPosition(function(r){
                                        if(this.getStatus() == BMAP_STATUS_SUCCESS){
                                            var geoc = new BMap.Geocoder();
                                            var pt = new BMap.Point(e.point.lng,  e.point.lat);//实例化这两个点
                                            geoc.getLocation(pt, function (rs) {
                                                var addComp = rs.addressComponents;
                                            });

                                        }else {
                                            alert('failed'+this.getStatus());
                                        }
                                    },{enableHighAccuracy : true});
                                });
                            /*}
                        });
                    }else{
                        fail();
                    }
                }
            });
        });*/



        var isQuery = true;
        var mapRes = { };
        var mapOpt = { };

        var local = new BMap.LocalSearch('长沙', {
            pageCapacity: 20,
            onSearchComplete: function(result){
                isQuery = true;
                $("#wordMap li").remove();
                var arr = [];
                if (local.getStatus() == BMAP_STATUS_SUCCESS) {
                    for (var i = 0; i < result.getCurrentNumPois(); i++) {
                        var item = result.getPoi(i);
                        if (!item.title || (item.tags && !item.tags.length) || !item.province || !item.address || !item.point.lng || /市$/.test(item.title) || /省$/.test(item.title) || /^朝阳区$/.test(item.title)) {
                            continue
                        }
                        var isTag = true;
                        item.tags = item.tags ? item.tags : [];
                        for (var j = 0; j < item.tags.length; j++) {
                            var tag = item.tags[j];
                            if (tag == '区县' || tag == '行政地标' || tag == '地级市' || tag == '名称标注类' || tag == '公交车站') {
                                isTag = false;
                                break
                            }
                        }
                        if (!isTag) {
                            continue;
                        }
                        var distance = parseInt(getFlatternDistance(string_y,string_x,item.point.lat,item.point.lng));

                        if(distance > 1000){
                            distance = parseFloat(distance / 1000).toFixed(2) + 'km';
                        }else{
                            distance = distance + 'm';
                        }
                        var list = $("<li class='cf'><a href='javascript:;'>" +
                                            "<div class='word_img'><img src='/mall2/images/adty.png'></div>" +
                                            "<div class='word_text'><div class='text_title'>"+item.title+"</div><p>" + item.address + "</p></div>" +
                                            "<div class='word_distance'>" + distance + "</div>" +
                                      "</a></li>");
                        list.data("lat", item.point.lat);
                        list.data("lng", item.point.lng);
                        list.data("city", result.city);
                        list.data("province", result.province);
                        list.data("address", item.address);
                        list.data("title", item.title);
                        // 关键字加红色
                        var re = new RegExp(result.keyword);
                        item.title = item.title.replace(re, '<b>' + result.keyword + '</b>');

                        arr.push(list[0]);
                    }
                    // 排序
                    arr = fieldsSort(arr, '+dis', "");
                    for (var x in arr) {
                        var items = arr[x];
                        $(items).appendTo($("#wordMap"));
                    }
                }
            }
        });

        function fail() {
            alert('定位失败');
        }

        // 定义周边POI检索类
        var POI = new BMap.Geocoder();

        function getPois(x,y){
            //var point = new BMap.Point(112.89211,28.214494);
            var point = new BMap.Point(x,y);
            POI.getLocation(point,function(res){

                $("#wordMap li").remove();
                var arr = [];
                for(var i in res.surroundingPois){
                    var item = res.surroundingPois[i];
                    if (!item.title || !item.address) {
                        continue;
                    }
                    var distance = parseInt(getFlatternDistance(string_y,string_x,item.point.lat,item.point.lng));
                    if(distance > 1000){
                        distance = parseFloat(distance / 1000).toFixed(2) + 'km';
                    }else{
                        distance = distance + 'm';
                    }
                    var list = $("<li class='cf'><a href='javascript:;'>" +
                                        "<div class='word_img'><img src='/mall2/images/adty.png'></div>" +
                                        "<div class='word_text'><div class='text_title'>"+item.title+"</div><p>" + item.address + "</p></div>" +
                                        "<div class='word_distance'>" + distance + "</div>" +
                                  "</a></li>");
                    list.data("lng", item.point.lng);
                    list.data('lat', item.point.lat);
                    list.data("latlog", item.point.lng + ',' + item.point.lat);
                    list.data("city", res.addressComponents.city);
                    list.data("province", res.addressComponents.province);
                    list.data("address", res.address);
                    list.data("district", res.addressComponents.district);
                    list.data("title", item.title);
                    arr.push(list[0]);
                }

                arr = fieldsSort(arr, '+dis', "");
                for (var x in arr) {
                    var items = arr[x];
                    $(items).appendTo($("#wordMap"))
                }
            },{
                poiRadius : 3000,
                numPois : 10
            });
        }


        // 搜索框 联想搜索
        $("#search").on("input",function() {
            if(!isQuery || $(this).val() == "" ) return;
            $("#wordMap li").remove();
            isQuery = false;
            local.search($("#search").val().trim(),{forceLocal: true});
        });

        // 搜索框聚焦
        $(document).on('focus','#search',function(){
            $(this).trigger("input");
        });

        $(document).on('click','#wordMap li',function () {
//                base.zb = $(this).data('latlog');
//                var diqu = $(this).data('address');
            var    lng=$(this).data('lng');
            var    lat=$(this).data('lat');
            var  province =$(this).data('province');
            var city =$(this).data('city');
            var  title = $(this).data('title');

            if(!$(this).data('district')){
                $.ajax({
                    url: "http://api.map.baidu.com/geocoder/v2/?",
                    type: "get",
                    async: false,
                    data: {
                        coordtype: 'wgs84ll',
                        location: lat + "," + lng,
                        ak: 'pRtqXqnajTytAzWDL3HOnPRK',
                        //callback: 'renderReverse',
                        output: 'json',
                        pois: 1
                    },
                    dataType: "jsonp",
                    success: function (geo_res) {
                        var option = {};
                        if (geo_res.status != 0) {
                            //alert('转换失败!');
                            return;
                        }

                        county = geo_res.result.addressComponent.district;
                        location.href = '/address/save?id=' + id + '&province=' + province + '&city=' + city +
                            '&county=' + county + '&address=' + title + '&contact=' + contact + '&phone=' + phone +
                            '&sex=' + sex + '&housemember=' + housemember + '&lng=' + lng + '&lat=' + lat + '&refer=' + refer;
                    }
                });
            }else{
                county = $(this).data('district');
                location.href = '/address/save?id=' + id + '&province=' + province + '&city=' + city +
                    '&county=' + county + '&address=' + title + '&contact=' + contact + '&phone=' + phone +
                    '&sex=' + sex + '&housemember=' + housemember + '&lng=' + lng + '&lat=' + lat + '&refer=' + refer;
            }

        });


        // 计算距离
        function count(lat_a, lng_a, lat_b, lng_b) {
            var pk = 180 / 3.14169;
            var a1 = lat_a / pk;
            var a2 = lng_a / pk;
            var b1 = lat_b / pk;
            var b2 = lng_b / pk;
            var t1 = Math.cos(a1) * Math.cos(a2) * Math.cos(b1) * Math.cos(b2);
            var t2 = Math.cos(a1) * Math.sin(a2) * Math.cos(b1) * Math.sin(b2);
            var t3 = Math.sin(a1) * Math.sin(b1);
            var tt = Math.acos(t1 + t2 + t3);
            return 6366000 * tt
        }
        // 微信分享
        var wx_config = {
            tag: '定位'
        };

        // 排序
        var fieldsSort = function(arr,field1,field2) {
            var char1=field1.charAt(0),
                char2=field1.charAt(0),
                dir1=char1==="-"?-1:1,
                dir2=char2==="-"?-1:1;
            if(char1==="-"||char1==="+")field1=field1.substr(1);
            if(char2==="-"||char2==="+")field2=field2.substr(1);
            arr.sort(function(a,b){
                return a[field1]===b[field1]?(a[field2]-b[field2])*dir2:(a[field1]-b[field1])*dir1;
            });
            return arr;
        };
    </script>
{/literal}
{include 'footer.tpl'}